<?php

namespace Management\Controller;

use Think\Controller;

use Myself\FileSystem;

class OrderController extends BaseController {


	//公众号的
	protected $appid = '';
	protected $appsecret = '';
	protected $m = NULL;

	protected $m_class = NULL;

	protected $m_config = NULL;

    protected $statusArr=array(

//        0.未付款 1. 未发货 2. 发货中 3. 已完成 4. 订单完成 5. 超时取消

        ['color'=>'dark','status'=>"未付款"],
        ['color'=>'default','status'=>"待分配"],
        ['color'=>'default','status'=>"已分配"],
        ['color'=>'blue','status'=>"司机到达"],
        ['color'=>'green','status'=>"待评价"],
        ['color'=>'dark','status'=>"评价完成"],
        ['color'=>'red','status'=>"已退款"],
        ['color'=>'default','status'=>"已取消"],

    );

    protected $statusdetail=array("尚未接单","分配订单","确认接单","到达出发地","装货完成","拍照完成","到达目的地","确认账单","确认二联单");


    //获取公众号基础功能token
    public function access_token($appid,$appsecret){
        $config = M('wx_config')->where(['id'=>1])->find();
        if($config['wx_time']<time()){
            $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
            $res = sendGet($url);
            $info = json_decode($res,true);
        	// ll($info);die;
            $up = M('wx_config')->where(['id'=>1])->save(['wx_token'=>$info['access_token'],'wx_time'=>time()+3600]);
            return $info['access_token'];
        }else{
            return $config['wx_token'];
        }
    }

    //司机分配模板消息
     public function WXtemplate_send($order_id='',$template_id='XC9VZgpXRjEt6BCzeUhKl8m2MOjC6n4RNOt28qp6mlc'){
        $token = $this->access_token($this->appid,$this->appsecret);
        // echo $token;die;
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$token;
        $order = M('order')->field(['driver_id','order_no','car_id'])->where(['id'=>$order_id])->find();
        $openid = M('driver')->where(['id'=>$order['driver_id']])->getField('wx_openid');//司机
        $return="";
        //模板
        $arr['touser'] = $openid;
        $arr['template_id'] = $template_id;
        $arr['url'] = $return;
        $arr['miniprogram']=array(
        	'appid'=>'wx7d361144397d04b7',
        	// 'page'=>'pages/driver/index/index'
        	// 'pagepath'=>'pages/driver/index/index'
        );
        $arr['data'] = array(
            "first"=>array("value"=>'订单分配通知',"color"=>'#173177'),
            "waybillNo"=>array("value"=>$order['order_no'],"color"=>'#173177'),
            "remark"=>array("value"=>'平台已为您分配订单，请及时进入小程序查看详情',"color"=>'#173177'),
        );
        $info = json_encode($arr,JSON_UNESCAPED_UNICODE);
        $res = sendPost($url,$info);
        // ll($res);die;
        $res = json_decode($res,true);
        return true;
        // $this->ajaxReturn($res);exit;
    }

	public function _initialize(){

		parent::_initialize();

		$this->m = M('order');
		$info = M('wx_base')->where(['id'=>1])->find();
		$this->appid = $info['appid'];
		$this->appsecret = $info['appsecret'];
		// $this->m_class = M('news_class');
		// $this->m_config = M('news_config');	

	}


	//待分配订单
    public function wait_order(){ 
		header('Content-Type:text/html;charset=utf-8');
		$where['status']=1;
		// $where['is_del']=0;
		//-----------------搜索-------------------
		if(I('product_id')){
			$where['product_id']=I('product_id');
			$this->assign('product_id',I('product_id'));
		}
        $key = I('key','');//关键字 订单号
		if(!empty($key)){
			$where['order_no|tel'] = array('LIKE','%'.$key.'%');
		}
		$from_time = I('from_time','');
		$to_time = I('to_time','');
		if($from_time){
			$from_time_s = strtotime($from_time);
			$where['addtime']= array('EGT',$from_time_s);
		}
		if($to_time){
			$to_time_s = strtotime($to_time)+86400;
			$where['addtime']= array('ELT',$to_time_s);
		}
		if($from_time && $to_time){
			$where['addtime']=array(array('EGT',$from_time_s),array('ELT',$to_time_s),'and');
		}
		//-------------------------搜索end-----------------
		$pageno = I('p',1,'int');
		$pageCount = 10;
		$list = $this->m->where($where)->page($pageno.','.$pageCount)->order('id desc')->select();

		$memberIdList=array_column($list,'member_id');
		$memberList=M('member')->where([
		    'id'=>['in',$memberIdList]
        ])->field('id,nickname,username,avatar')->select();
        $memberList=array_column($memberList,null,'id');
        $this->assign('memberList',$memberList);
        //--------------------订单详情-------------------------------
        foreach ($list as $k=>$v){
            $list[$k]['detail']=M('order_detail')->where(['order_no'=>$v['order_no']])->field('pic_path,title_cn')->select();
        }
		$this->assign('list',$list);// 赋值数据集
		$count = $this->m->where($where)->count();// 查询满足要求的总记录数
		$this->assign('count',$count);// 赋值分页输出	
		$Page = new \Think\Page($count,$pageCount);// 实例化分页类 传入总记录数和每页显示的记录数
		$show = $Page->showManage();// 分页显示输出
		$this->assign('page',$show);// 赋值分页输出
        //-------------------------固定参数输出-----------------
        $this->assign('statusArr',$this->statusArr);// 状态
		$this->display('index');
    }
		

	

	

    public function index(){ 

		header('Content-Type:text/html;charset=utf-8');

		// $where['is_del']=0;

		//-----------------搜索-------------------
		if(!empty(I('add_start')) && !empty(I('add_end'))){
			$this->assign('add_start',I('add_start'));
			$this->assign('add_end',I('add_end'));
			$add_start = I('add_start').' 00:00:00';
			$add_end = I('add_end').' 23:59:50';
			$where['addtime'] = array('between',[$add_start,$add_end]);
		}
		if(!empty(I('booking_start')) && !empty(I('booking_end'))){
			$this->assign('booking_start',I('booking_start'));
			$this->assign('booking_end',I('booking_end'));
			$booking_start = I('booking_start').' 00:00:00';
			$booking_end = I('booking_end').' 23:59:50';
			$where['booktime'] = array('between',[$booking_start,$booking_end]);
		}
		if(I('product_id')){
			$where['product_id']=I('product_id');
			$this->assign('product_id',I('product_id'));
		}
		if(!empty(I('is_online'))){
			$where['is_online']=I('is_online');
			$this->assign('is_online',I('is_online'));
		}
		if(!empty(I('from'))){
			if(I('from')==1){
				$where['from']='';
			}elseif(I('from')==2){
				$where['from']='baidu';
			}
			$this->assign('from',I('from'));
		}
		if(I('cartype_id')){
			$where['cartype_id']=I('cartype_id');
			$this->assign('cartype_id',I('cartype_id'));
		}
		if(I('status')!=''){
			$where['status']=I('status');
			$this->assign('status',I('status'));
		}
		if(I('driver_id')!=''){
			$where['driver_id']=I('driver_id');
			$this->assign('driver_id',I('driver_id'));
		}
        $key = I('key','');//关键字 订单号

		if(!empty($key)){

			$where['order_no|tel'] = array('LIKE','%'.$key.'%');

		}



		$from_time = I('from_time','');

		$to_time = I('to_time','');

		if($from_time){

			$from_time_s = strtotime($from_time);

			$where['addtime']= array('EGT',$from_time_s);

		}

		if($to_time){

			$to_time_s = strtotime($to_time)+86400;

			$where['addtime']= array('ELT',$to_time_s);

		}

		if($from_time && $to_time){

			$where['addtime']=array(array('EGT',$from_time_s),array('ELT',$to_time_s),'and');

		}

		//-------------------------搜索end-----------------

		$pageno = I('p',1,'int');

		$pageCount = 10;

		$list = $this->m->where($where)->page($pageno.','.$pageCount)->order('id desc')->select();

		$memberIdList=array_column($list,'member_id');

		$memberList=M('member')->where([

		    'id'=>['in',$memberIdList]

        ])->field('id,nickname,username,avatar')->select();

        $memberList=array_column($memberList,null,'id');

        $this->assign('memberList',$memberList);

        //--------------------订单详情-------------------------------

        foreach ($list as $k=>$v){

            $list[$k]['detail']=M('order_detail')->where(['order_no'=>$v['order_no']])->field('pic_path,title_cn')->select();

        }

		$this->assign('list',$list);// 赋值数据集

		$count = $this->m->where($where)->count();// 查询满足要求的总记录数

		$this->assign('count',$count);// 赋值分页输出	

		$Page = new \Think\Page($count,$pageCount);// 实例化分页类 传入总记录数和每页显示的记录数

		$show = $Page->showManage();// 分页显示输出

		$this->assign('page',$show);// 赋值分页输出

        //-------------------------固定参数输出-----------------
		//司机筛选
		$driver =M('driver')->field(['id','realname'])->where('type=1')->select();
        $this->assign('driver',$driver);// 状态
        $this->assign('statusArr',$this->statusArr);// 状态
        $product = M('product')->field(['id','title'])->select();
        $this->assign('product',$product);// 搬家模式(订单类型)
        $cartype = M('cartype')->field(['id','title'])->select();
        $this->assign('cartype',$cartype);// 车辆类型
		$this->display('index');

    }

	public function edit(){
		$id = I('id',0,'int');
		$order = $this->m->find($id);
		$order['driver_tel'] =M('driver')->where(['id'=>$order['driver_id']])->getField('mobile');
		$order['receipt'] = json_decode($order['receipt']);
		$order['relay'] = json_decode($order['relay']);
		$order['delivery_address'] = json_decode($order['delivery_address']);
		$member = M('member')->find($order['member_id']);
		$order['member'] = $member['username'];
		$detail = M('order_detail')->where('order_no ="'.$order['order_no'].'"')->select();
		foreach($detail as $k=>$v){
			$detail[$k]['attribute_cn'] = json_decode($detail[$k]['attribute_cn']);
		}
		$order['detail'] = $detail;
		//客服备注信息
		$kflist = M('order_kf')->where(['order_id'=>$id])->select();
		$this->assign('kflist',$kflist);
		$this->assign('order',$order);
		$this->assign('startpoint',$order['startpoint']);
		$this->assign('endpoint',$order['endpoint']);
		$this->assign('back_url',$_SERVER['HTTP_REFERER']);
        $this->assign('statusArr',$this->statusArr);// 状态
        $this->assign('statusdetail',$this->statusdetail);// 状态
        // var_dump(M('driver')->where(['cartype_id'=>json_decode($order['cartype_info'])->cartype_id])->select());
        $this->assign('driverList',M('driver')->where(['cartype_id'=>json_decode($order['cartype_info'])->cartype_id])->select());
          //搬家类型楼层
        $this->assign('productList',M('product')->select());
        //车型
        $this->assign('cartypeList',M('cartype')->select());
        //搬家类型对应可选楼层
        $floor_cost = M('product')->where(['id'=>$order['product_id']])->getField('floor_cost');
        $this->assign('floor_cost',json_decode($floor_cost,true));//选择楼层
        //额外费用添加
        $attachment = M('attachment')->where('type!=4 and type!=5 and product_id='.$order['product_id'])->select();
        if(!empty($attachment)){
        	foreach ($attachment as $k=> $v) {
        		$child = M('attachment_option')->where(['attachment_id'=>$v['id']])->select();
        		if(!empty($child)){
        			foreach ($child as $a => $b) {
        				$child[$a]['num']=0;
        			}
        		}
        		$attachment[$k]['child'] = $child;
        	}
        }
        $order_atta=json_decode($order['attachment'],true);
        // ll($order_atta['list']);die;
        if(!empty($order_atta['list'])){
        	foreach($order_atta['list'] as $q=>$w){
        		foreach($attachment as $e=>$r){
        			if($r['id']==$w['option_id']){
        				foreach($r['child'] as $t=>$y){
        					if($y['id']==$w['attachment_id']){
        						$attachment[$e]['child'][$t]['num'] = $w['num'];
        					}
        				}
        			}
        		}
        	}
        }
        // ll($attachment);die;
        $this->assign('attachmentList',$attachment);
		$this->display('edit');

    }
    //保存订单
	public function save(){
		$data = I('post.');
		// ll($data);die;
		$order = M('order')->where(['id'=>$data['id']])->find();
		// if(!empty($data['is_attachment'])){
			//未选中修改附加项 不修改
		if(!empty($data['attachment'])){
			$attachment =[];
			$atta = json_decode(htmlspecialchars_decode($data['attachment']),true);
			if(!empty($atta)){
				foreach ($atta as $k => $v) {
					if(!empty($v['child'])){
						foreach ($v['child'] as $a => $b) {
							// ll($b);
							if($b['num']>0){
								array_push($attachment,$b);
							}
						}
					}
				}
			}
			$attach_price =0;
			if(!empty($attachment)){
				foreach ($attachment as $key=>$value){
					// ll($value);
				 	$attachment[$key]['attachment_title']=M('attachment')->where(['id'=>$value['attachment_id']])->getField('title');
				 	$attachment[$key]['price']=$value['num']*$value['value'];
				 	$attachment[$key]['option_id']=$value['attachment_id'];//父类id
				 	$attachment[$key]['attachment_id']=$value['id'];//子类id
		            $res=M('attachment_option')->find($value->id);
		            $attach_price+=$value['num']*$value['value'];
		        }
		    }
	        $arr['attachment']=json_encode(['list'=>$attachment,'price'=>$attach_price]);
		}

		$productInfo=M('product')->where(['id'=>$data['product_id']])->find();
		$cartypeInfo=M('cartype')->where(['id'=>$data['cartype_id']])->find();
		$floorInfo=json_decode($productInfo['floor_cost'],true);
		if($data['product_id']==1){
			$flag_fall_price = $cartypeInfo['flag_fall_price'];//起步价
			$over_charge = $cartypeInfo['over_charge'];//超公里
		}elseif($data['product_id']==2){
			$flag_fall_price = $cartypeInfo['out_price'];//起步价
			$over_charge = $cartypeInfo['out_over_charge'];//超公里
		}else{
			$flag_fall_price = $cartypeInfo['jp_price'];//起步价
			$over_charge = $cartypeInfo['jp_over_charge'];//超公里
		}
		if($data['mile']<=10)
            $car_price=$flag_fall_price;
        else
            $car_price=$flag_fall_price+($data['mile']-10)*$over_charge;
     	$status = M('order')->where(['id'=>$data['id']])->getField('status');//订单状态
        if($status==0){
        	$order_no = 'BJ'.date('YmdHis').$data['member_id'];
        	//未付款才可以变更订单号不然无法退款
			$arr['order_no']=$order_no;//预付款订单号
			$arr['order_no_small'] = date('YmdHis').time().$data['member_id'];//尾款订单号
        }
        $arr['status']=$data['status'];
		// ll($arr);die;
		$arr['cartype_info']=json_encode([
            'cartype_id'		=>$cartypeInfo['id'],
            'cartype_title'		=>$cartypeInfo['title'],
            'flag_fall_price'	=>$cartypeInfo['flag_fall_price'],
            'over_charge'		=>$cartypeInfo['over_charge'],
            'mile'				=>$data['mile'],
            'price'				=>$car_price
         ]);
		$arr['product_info']=json_encode([
            'product_id'		=>$data['product_id'],
            'product_title'		=>$productInfo['title'],
            'floor_from'		=>$data['floor_from'],
            'floor_to'			=>$data['floor_to'],
            'floor_from_cost'	=>$data['floor_from_cost'],
            'floor_to_cost'		=>$data['floor_to_cost'],
            'price'				=>$data['floor_from_cost']+$data['floor_to_cost']
        ]);
        $arr['remark'] 		    = $data['remark'];//用户备注
        $arr['addtime'] 		= $data['addtime'];
        $arr['booktime'] 		= $data['booktime'];
        $arr['total_price'] 	= $data['total_price'];//总价
        $arr['advance_price'] 	= $data['advance_price'];
        $arr['extra_price'] 	= $data['extra_price'];
        $arr['arrival'] 		= $data['arrival'].$data['end_detail'];
        $arr['departure'] 		= $data['departure'].$data['start_detail'];
        $arr['tel'] 			= $data['tel'];
        $arr['small_balance'] 	= $data['small_balance'];
        $arr['move_price'] 		= $data['move_price'];
        $arr['product_id'] 		= $data['product_id'];
        $arr['member_id'] 		= $data['member_id'];
        $arr['mile'] 			= $data['mile'];
        $arr['startpoint']      =json_encode(['latitude'=>$data['start_lat'],'longitude'=>$data['start_lng']]);
        $arr['endpoint']        =json_encode(['latitude'=>$data['end_lat'],'longitude'=>$data['end_lng']]);
        // ll($arr);die;
        $res = M('order')->where(['id'=>$data['id']])->save($arr);

		if($data['id']){

			$this->selectPage_ajax(array('act' => '修改', 'back_url' =>  U('Order/index'),'jump_url' => U('Order/edit','id='.$data['id'])));
		}else{
		    $result = $this->m->add($temp);
			if($result)
			    $this->selectPage_ajax( array('act' => '添加', 'back_url' => I('back_url'),'jump_url' => U('Order/index')));
			else $this->error($GLOBALS['notice']['error'][0]);
		}
	}


	public function del(){
		$ids = I('id');
		if($ids){
			if(is_array($ids)){$ids=implode(",",$ids);}
			$this->baseDelFile('ticket',$ids,'pic_path');
			if ($this->m->delete($ids)){
				$ids=explode(",",$ids);
			    $this->success($GLOBALS['notice']['success'][1]);
			}else{
				$this->error($GLOBALS['notice']['error'][1]);
			}
		}else{
			$this->error($GLOBALS['notice']['warming'][1]);
		}		
    }

	public function batch(){          ////批量操作方法
		$ids = I('id');
		$val = I('get.val');
		$field = I('get.field');
		if($ids){
			if(is_array($ids)){$ids=implode(",",$ids);}
			if ($this->m->where('id in ('.$ids.')')->save(array($field=>$val))){
				$ids=explode(",",$ids);
			    $this->success($GLOBALS['notice']['success'][2]);
			}else{
				$this->error($GLOBALS['notice']['error'][2]);
			}
		}else{
			$this->error($GLOBALS['notice']['warming'][1]);
		}		
    }

	public function ajaxFindNext(){
		$selValue = I('selValue','0','int');
		$areaNextId = I('areaNextId','','int');
		$domId = I('domId');
		$classList = $selValue?$this->m_class->where('parent_id='.$selValue)->select():array();
		$content = "";
		if(!count($classList)){
			echo 0;exit;
		}else{
			$content .= '<span id="'.$domId.'_'.$areaNextId.'">'."\n\t";
			$content .= '<select class="form-control input-small" name="class_id[]" onchange="javascript:findNext(this.value , '.$areaNextId.' , \''.$domId.'\')">'."\n\t";
			$content .= '<option value="0">请选择</option>'."\n\t";
			foreach($classList as $item){
			$selectedMark = $selValue==$item['id']?'selected':'';
			$content .= '<option value="'.$item['id'].'" '.$selectedMark.'>'.$item['class_name'].'</option>'."\n\t";
			}
			$content .= '</select>'."\n\t";
			$content .= '</span>'."\n\t";
			echo $content;exit;
		}
	}
	public function ajaxListInput(){
		header('Content-Type:text/html;charset=utf-8');
		$info = I('post.');
		$data[$info["fieldName"]] = $info["Val"];
		$data["id"] = $info["id"];
		if ($this->m->save($data)){
			echo "success";
		}else{
			echo "error";
		}
		exit;
	}

	public function orderajax(){

	    $data['status'] = 2;
        $relay['company'] = I('kdgs');
        $relay['number'] = I('kddh');
        $data['relay'] = json_encode($relay);
        $id = I('orderid');
        $this->m->where('id='.$id)->save($data);
        $this->ajaxReturn(1);
    }
        //意向记录详情
	public function again_edit(){
		$id = I('id',0,'int');
		$order = $this->m->find($id);
		$this->assign('oldatta',base64_encode($order['attachment']));//原有额外属性编码
		$order['driver_tel'] =M('driver')->where(['id'=>$order['driver_id']])->getField('mobile');
		$order['receipt'] = json_decode($order['receipt']);
		$order['relay'] = json_decode($order['relay']);
		$order['delivery_address'] = json_decode($order['delivery_address']);
		$member = M('member')->find($order['member_id']);
		$order['member'] = $member['username'];
		$detail = M('order_detail')->where('order_no ="'.$order['order_no'].'"')->select();
		foreach($detail as $k=>$v){
			$detail[$k]['attribute_cn'] = json_decode($detail[$k]['attribute_cn']);
		}
		$order['detail'] = $detail;
		//客服备注信息
		$kflist = M('order_kf')->where(['order_id'=>$id])->select();
		$this->assign('kflist',$kflist);
		$this->assign('order',$order);
		$this->assign('startpoint',$order['startpoint']);
		$this->assign('endpoint',$order['endpoint']);
		$this->assign('back_url',$_SERVER['HTTP_REFERER']);
        $this->assign('statusArr',$this->statusArr);// 状态
        $this->assign('statusdetail',$this->statusdetail);// 状态
        // var_dump(M('driver')->where(['cartype_id'=>json_decode($order['cartype_info'])->cartype_id])->select());
        $this->assign('driverList',M('driver')->where(['cartype_id'=>json_decode($order['cartype_info'])->cartype_id])->select());
          //搬家类型楼层
        $this->assign('productList',M('product')->select());
        //车型
        $this->assign('cartypeList',M('cartype')->select());
        //搬家类型对应可选楼层
        $floor_cost = M('product')->where(['id'=>$order['product_id']])->getField('floor_cost');
        $this->assign('floor_cost',json_decode($floor_cost,true));//选择楼层
        //额外费用添加
        $attachment = M('attachment')->where('type!=4 and type!=5 and product_id='.$order['product_id'])->select();
        if(!empty($attachment)){
        	foreach ($attachment as $k=> $v) {
        		$child = M('attachment_option')->where(['attachment_id'=>$v['id']])->select();
        		if(!empty($child)){
        			foreach ($child as $a => $b) {
        				$child[$a]['num']=0;
        			}
        		}
        		$attachment[$k]['child'] = $child;
        	}
        }
        $order_atta=json_decode($order['attachment'],true);
        // ll($order_atta['list']);die;
        if(!empty($order_atta['list'])){
        	foreach($order_atta['list'] as $q=>$w){
        		foreach($attachment as $e=>$r){
        			if($r['id']==$w['option_id']){
        				foreach($r['child'] as $t=>$y){
        					if($y['id']==$w['attachment_id']){
        						$attachment[$e]['child'][$t]['num'] = $w['num'];
        					}
        				}
        			}
        		}
        	}
        }
        // ll($attachment);die;
        $this->assign('attachmentList',$attachment);
		$this->display('again');
    }
    //weapon意向下单
	public function again_save(){
		$data = I('post.');
		// ll($data);die;
		$order = M('order')->where(['id'=>$data['id']])->find();
		if(!empty($data['attachment'])){
			$attachment =[];
			$atta = json_decode(htmlspecialchars_decode($data['attachment']),true);
			if(!empty($atta)){
				foreach ($atta as $k => $v) {
					if(!empty($v['child'])){
						foreach ($v['child'] as $a => $b) {
							// ll($b);
							if($b['num']>0){
								array_push($attachment,$b);
							}
						}
					}
				}
			}
			$attach_price =0;
			if(!empty($attachment)){
				foreach ($attachment as $key=>$value){
					// ll($value);
				 	$attachment[$key]['attachment_title']=M('attachment')->where(['id'=>$value['attachment_id']])->getField('title');
				 	$attachment[$key]['price']=$value['num']*$value['value'];
				 	$attachment[$key]['option_id']=$value['attachment_id'];//父类id
				 	$attachment[$key]['attachment_id']=$value['id'];//子类id
		            $res=M('attachment_option')->find($value->id);
		            $attach_price+=$value['num']*$value['value'];
		        }
		    }
	        $arr['attachment']=json_encode(['list'=>$attachment,'price'=>$attach_price]);
		}else{
			$arr['attachment'] = base64_decode($data['oldatta']);//额外大件没有变化则取原有json串
		}
		$productInfo=M('product')->where(['id'=>$data['product_id']])->find();
		$cartypeInfo=M('cartype')->where(['id'=>$data['cartype_id']])->find();
		$floorInfo=json_decode($productInfo['floor_cost'],true);
		if($data['product_id']==1){
			$flag_fall_price = $cartypeInfo['flag_fall_price'];//起步价
			$over_charge = $cartypeInfo['over_charge'];//超公里
		}elseif($data['product_id']==2){
			$flag_fall_price = $cartypeInfo['out_price'];//起步价
			$over_charge = $cartypeInfo['out_over_charge'];//超公里
		}else{
			$flag_fall_price = $cartypeInfo['jp_price'];//起步价
			$over_charge = $cartypeInfo['jp_over_charge'];//超公里
		}
		if($data['mile']<=10)
            $car_price=$flag_fall_price;
        else
            $car_price=$flag_fall_price+($data['mile']-10)*$over_charge;
        
     	// $status = M('order')->where(['id'=>$data['id']])->getField('status');//订单状态
    	$order_no = 'BJ'.date('YmdHis').$data['member_id'];
    	//未付款才可以变更订单号不然无法退款
		$arr['order_no']=$order_no;//预付款订单号
		$arr['order_no_small'] = date('YmdHis').time().$data['member_id'];//尾款订单号
        $arr['status']=$data['status'];
		// ll($arr);die;
		$arr['cartype_info']=json_encode([
            'cartype_id'		=>$cartypeInfo['id'],
            'cartype_title'		=>$cartypeInfo['title'],
            'flag_fall_price'	=>$cartypeInfo['flag_fall_price'],
            'over_charge'		=>$cartypeInfo['over_charge'],
            'mile'				=>$data['mile'],
            'price'				=>$car_price
         ]);
		$arr['product_info']=json_encode([
            'product_id'		=>$data['product_id'],
            'product_title'		=>$productInfo['title'],
            'floor_from'		=>$data['floor_from'],
            'floor_to'			=>$data['floor_to'],
            'floor_from_cost'	=>$data['floor_from_cost'],
            'floor_to_cost'		=>$data['floor_to_cost'],
            'price'				=>$data['floor_from_cost']+$data['floor_to_cost']
        ]);
        $arr['remark'] 		    = $data['remark'];//用户备注
        $arr['addtime'] 		= $data['addtime'];
        $arr['booktime'] 		= $data['booktime'];
        $arr['total_price'] 	= $data['total_price'];//总价
        $arr['advance_price'] 	= $data['advance_price'];
        $arr['extra_price'] 	= $data['extra_price'];
        $arr['arrival'] 		= $data['arrival'];
        $arr['departure'] 		= $data['departure'];
        $arr['tel'] 			= $data['tel'];
        $arr['small_balance'] 	= $data['small_balance'];
        $arr['move_price'] 		= $data['move_price'];
        $arr['product_id'] 		= $data['product_id'];
        $arr['member_id'] 		= $data['member_id'];
        $arr['mile'] 			= $data['mile'];
        $arr['startpoint']      =json_encode(['latitude'=>$data['start_lat'],'longitude'=>$data['start_lng']]);
        $arr['endpoint']        =json_encode(['latitude'=>$data['end_lat'],'longitude'=>$data['end_lng']]);
        // ll($arr);die;
        $res = M('order')->add($arr);
        if($res){
        	$del = M('order_valuation')->where(['id'=>$data['id']])->delete();
     		$this->selectPage_ajax( array('act' => '帮助下单操作', 'back_url' =>U('Order/index'),'jump_url' => U('Order/index')));
        }else{
        	$this->selectPage_ajax(['act'=>'操作未']);
        }
	}
	//weapon司机分配单独分配(二期修改问车辆分配)
	public function driver_edit(){
		$id = I('id',0,'int');//订单id
		$order = $this->m->where('id='.$id)->find();
		$car = M('car')->where('1=1')->select();
		$carList=[];
		if(!empty($car)){
			foreach ($car as $k => $v) {
				// $isset = M('order')->where("(status=2 or status=3) and car_id=".$v['car_id'])->find();
				$isset = M('order')->where("status=3 and car_id=".$v['car_id'])->find();
				if(empty($isset)){
					array_push($carList,$v);
				}
			}
		}
		$this->assign('carList',$carList);
		$this->assign('order',$order);
		$this->display('driver_edit');
    }
    //确认分配司机
	public function driver_save(){
		$data = I('post.');
		// ll($data);die;
		$car = M('car')->where(['car_id'=>$data['car_id']])->find();//车辆详情
		if(empty($car['driver_id'])){
			$this->selectPage_ajax(array('act' => '车辆未绑定司机,操作未', 'back_url' =>U('Order/index'),'jump_url' => U('Order/driver_edit','id='.$data['id'])));
			exit;
		}
		// die;
        $info = M('driver')->where(['id'=>$car['driver_id']])->find();//绑定订单的司机
        if(!empty($info)){
	        $temp['driver_id'] = $info['id'];
	        $temp['driver_name']=$info['realname'];
	        $temp['driver_tel']=$info['mobile'];
	        $temp['car_name']=$info['car_name'];
        }
        $temp['car_id']=$data['car_id'];
    	//支付订单更改分配状态
    	$temp['driver_status']=1;
    	$temp['status']=2;
    	// ll($temp);die;
		if($data['id']){
			//已支付订单 可以分配
			$res = $this->m->where(['id'=>$data['id']])->save($temp);
			if(!empty($data['is_driver'])){;
				$r = $this->WXtemplate_send($data['id']);
			}
			$this->selectPage_ajax(array('act' => '修改', 'back_url' =>U('Order/index'),'jump_url' => U('Order/index','id='.$data['id'])));
		}else{
		    $result = $this->m->add($temp);
			if($result)
			    $this->selectPage_ajax( array('act' => '添加', 'back_url' => U('Order/index'),'jump_url' => U('Order/index')));
			else $this->error($GLOBALS['notice']['error'][0]);
		}
	}


	//协助用户下单
	public function help_order(){
		$id = I('id',0,'int');
		if(!empty($id)){
			//存在用户id则为线上订单2是线下订单1是线上订单
			$is_online=1;
		}else{
			$is_online=2;
		}
		$this->assign('is_online',$is_online);
		$this->assign('time',date('Y-m-d H:i:s',time()+3600));
		$this->assign('back_url',$_SERVER['HTTP_REFERER']);
		$this->assign('order_no','BJ'.time().$id);
		$this->assign('order_no_small',date('YmdHis').time().$id);
        $this->assign('statusArr',$this->statusArr);// 状态
        $this->assign('statusdetail',$this->statusdetail);// 状态
        // var_dump(M('driver')->where(['cartype_id'=>json_decode($order['cartype_info'])->cartype_id])->select());
        // $this->assign('driverList',M('driver')->where(['cartype_id'=>json_decode($order['cartype_info'])->cartype_id])->select());
          //搬家类型楼层
        $productList = M('product')->order('id asc')->select();
        $this->assign('productList',$productList);
        $floor_cost = M('product')->where(['id'=>I('product_id')])->getField('floor_cost');
        $this->assign('floor_cost',json_decode($floor_cost,true));//选择楼层
        // ll(M('product')->select());die;
        //车型
        $this->assign('cartypeList',M('cartype')->order('id asc')->select());
        //当前默认车型
        $this->assign('cartypeInfo',M('cartype')->order('id asc')->find());
        //额外费用添加
        $attachment = M('attachment')->where('type!=4 and type!=5 and product_id='.I('product_id'))->select();
        if(!empty($attachment)){
        	foreach ($attachment as $k=> $v) {
        		$child = M('attachment_option')->where(['attachment_id'=>$v['id']])->select();
        		if(!empty($child)){
        			foreach ($child as $a => $b) {
        				$child[$a]['num']=0;
        			}
        		}
        		$attachment[$k]['child'] = $child;
        	}
        }
        //可分配车辆
        $car = M('car')->where('1=1')->select();
		$carList=[];
		if(!empty($car)){
			foreach ($car as $k => $v) {
				$isset = M('order')->where("(status=2 or status=3) and car_id=".$v['car_id'])->find();
				if(empty($isset)){
					array_push($carList,$v);
				}
			}
		}
		$this->assign('carList',$carList);
        $this->assign('attachmentList',$attachment);
        $this->assign('product_id',I('product_id'));
        $this->assign('member_id',I('id'));
		$this->display('help_order');

    }
     //协助下单操作
	public function help_save(){
		// $this->selectPage_ajax( array('act' => '添加', 'back_url' => I('back_url'),'jump_url' => U('Order/index')));exit;
		$data = I('post.');
		// ll($data);die;
		$productInfo=M('product')->where(['id'=>$data['product_id']])->find();
		$cartypeInfo=M('cartype')->where(['id'=>$data['cartype_id']])->find();
        //mile起点终点距离
        $floorInfo=json_decode($productInfo['floor_cost'],true);
		if($data['product_id']==1){
			$flag_fall_price = $cartypeInfo['flag_fall_price'];//起步价
			$over_charge = $cartypeInfo['over_charge'];//超公里
		}elseif($data['product_id']==2){
			$flag_fall_price = $cartypeInfo['out_price'];//起步价
			$over_charge = $cartypeInfo['out_over_charge'];//超公里
		}else{
			$flag_fall_price = $cartypeInfo['jp_price'];//起步价
			$over_charge = $cartypeInfo['jp_over_charge'];//超公里
		}
		if($data['mile']<=10)
            $car_price=$flag_fall_price;
        else
            $car_price=$flag_fall_price+($data['mile']-10)*$over_charge;
        $arr=[
            'member_id'=>$data['member_id'],
            'is_online'=>$data['is_online'],//判断线上线下订单
            'order_no'=> $data['order_no'],
            'order_no_small'=> $data['order_no_small'],
            'addtime'=>date('Y-m-d H:i:s'),
            'status'=>$data['status'],
            'booktime'=>$data['booktime'],
            'departure'=>$data['departure'].$data['start_detail'],
            'arrival'=>$data['arrival'].$data['end_detail'],
            'remark'=>$data['remark'],
            'cartype_info'=>json_encode([
                'cartype_id'=>$cartypeInfo['id'],
                'cartype_title'=>$cartypeInfo['title'],
                'flag_fall_price'=>$cartypeInfo['flag_fall_price'],
                'over_charge'=>$cartypeInfo['over_charge'],
                'mile'=>$data['mile'],
                'price'=>$car_price
            ]),
            'product_info'=>json_encode([
                'product_id'=>$data['product_id'],
                'product_title'=>$productInfo['title'],
                'floor_from'=>$floorInfo[$data['floor_from']]['title'],
                'floor_to'=>$floorInfo[$data['floor_to']]['title'],
                'floor_from_cost'=>$floorInfo[$data['floor_from']]['price'],
                'floor_to_cost'=>$floorInfo[$data['floor_to']]['price'],
                'price'=>$product_price=$floorInfo[$data['floor_from']]['price']+$floorInfo[$data['floor_to']]['price']
            ]),
            'tel'=>$data['tel'],//客户联系方式
            'mile'=>$data['mile'],//距离
            'mile_price'=>$data['mile_price'],//超公里价格
            'product_id'=>$data['product_id'],//weapon搬家类型
            'cartype_id'=>$cartypeInfo['id'],//weapon车辆类型
            'from'=>$post['from'],//下单三方来源 百度/微信
            'startpoint'=>json_encode(['latitude'=>$data['start_lat'],'longitude'=>$data['start_lng']]),
            'endpoint'=>json_encode(['latitude'=>$data['end_lat'],'longitude'=>$data['end_lng']]),
        ];

        // ll($arr);die;
		$attach_price =0;
		$attachment =[];
        if(!empty($data['attachment'])){
			$atta = json_decode(htmlspecialchars_decode($data['attachment']),true);
    		// ll($atta);die;
			if(!empty($atta)){
				foreach ($atta as $k => $v) {
					if(!empty($v['child'])){
						foreach ($v['child'] as $a => $b) {
							if($b['num']>0){
								array_push($attachment,$b);
							}
						}
					}
				}
			}
		}
		// ll($attachment);die;
		if(!empty($attachment)){
			foreach ($attachment as $key=>$value){
			 	$attachment[$key]['attachment_title']=M('attachment')->where(['id'=>$value['attachment_id']])->getField('title');
			 	$attachment[$key]['price']=$value['num']*$value['value'];
			 	$attachment[$key]['option_id']=$value['attachment_id'];//父类id
			 	$attachment[$key]['attachment_id']=$value['id'];//子类id
	            $res=M('attachment_option')->find($value->id);
	            $attach_price+=$value['num']*$value['value'];
	        }
	    }
        $arr['attachment']=json_encode(['list'=>$attachment,'price'=>$attach_price]);
        $arr['advance_price']=$data['advance_price'];//预付款
        $arr['total_price']=$attach_price+$product_price+$car_price;
        $arr['small_balance']=$data['total_price']-$data['advance_price'];


        //分配司机start
        if(!empty($data['car_id'])){
        	$driver_id = M('car')->where(['car_id'=>$data['car_id']])->getField('driver_id');//车辆绑定司机的id
        	if(!empty($driver_id)){
				$info = M('driver')->where(['id'=>$driver_id])->find();//车辆绑定的司机的详情
		        if(!empty($info)){
			        $arr['driver_id'] = $info['id'];
			        $arr['driver_name']=$info['realname'];
			        $arr['driver_tel']=$info['mobile'];
			        $arr['car_name']=$info['car_name'];
			        $arr['driver_status']=1;//司机状态已分配
		        }
	        }
	        $arr['car_id']=$data['car_id'];
        }
		// ll($arr);die;
        //分配司机end
		$inc = M('order')->add($arr);
		//客服备注
		if(!empty($data['kfremark'])){
			$kf['order_id']=$inc;
			$kf['content']=$data['kfremark'];
			$kf['addtime'] = date('Y-m-d H:i:s',time());
    		$res = M('order_kf')->add($kf);
		}
		// echo $inc;die;
        if($inc){
        	if(!empty($data['is_driver'])){;
				$r = $this->WXtemplate_send($inc);
			}
			$this->selectPage_ajax(array('act' => '下单', 'back_url' => U('Order/index'),'jump_url' => U('Order/index')));
		}else{
			$this->selectPage_ajax( array('act' => '添加', 'back_url' => U('Order/index'),'jump_url' => U('Order/index')));
		}
	}
	//管理员取消订单
	public function qx_order(){
		$order_id = I('post.order_id');
		$res = $this->m->where(['id'=>$order_id])->save(['status'=>7,'cancel_time'=>date('Y-m-d H:i:s',time())]);
		if($res){
			$this->ajaxReturn(['status'=>1,'msg'=>'取消成功']);
		}else{
			$this->ajaxReturn(['status'=>2,'msg'=>'取消失败']);
		}
	}



	    //搬家类型选择计算起步价与超公里费用
    public function product_select(){
        $data = I('post.');
        $cartype = M('cartype')->where(['id'=>$data['cartype_id']])->find();
        $product = M('product')->where(['id'=>$data['product_id']])->find();
        $floor = json_decode($product['floor_cost'],true);//当前选中搬家类型对应楼层与价格
        // ll($floor);die;
        if($data['product_id']==1){
            //普通搬家
            $arr['flag_fall_price'] = $cartype['flag_fall_price'];
            $arr['over_charge'] = $cartype['over_charge'];
        }elseif($data['product_id']==2){
            //跨城搬家
            $arr['flag_fall_price'] = $cartype['out_price'];
            $arr['over_charge'] = $cartype['out_over_charge'];
        }else{
            //日式搬家
            $arr['flag_fall_price'] = $cartype['jp_price'];
            $arr['over_charge'] = $cartype['jp_over_charge'];
        }
        $this->ajaxReturn(['arr'=>$arr,'floor'=>$floor]);exit;
    }


    //时间标签标记
    public function title_edit(){
    	$id = I('id');
    	$order =M('order_valuation')->field(['id','title_content','title_time','content'])->where(['id'=>$id])->find();
    	$this->ajaxReturn($order);exit;
    }
    public function title_save(){
    	$data = I('post.');
    	$res =M('order_valuation')->where(['id'=>$data['id']])->save($data);
    	if($res){
    		$this->ajaxReturn(['status'=>1,'msg'=>'保存成功']);exit;
    	}else{
    		$this->ajaxReturn(['status'=>2,'msg'=>'暂无修改']);exit;
    	}
    }
    public function title_reset(){
    	$data = I('post.');
    	if($data['is_title']==1){
    		$res =M('order_valuation')->where(['id'=>$data['id']])->save(['is_title'=>0]);	
    	}else{
    		$res =M('order_valuation')->where(['id'=>$data['id']])->save(['is_title'=>1]);	
    	}
    	if($res){
    		$this->ajaxReturn(['status'=>1,'msg'=>'修改成功']);exit;
    	}else{
    		$this->ajaxReturn(['status'=>2,'msg'=>'修改失败']);exit;
    	}
    }

    //客服备注保存
    public function kf_save(){
    	$data = I('post.');
    	$data['addtime'] = date('Y-m-d H:i:s',time());
    	$res = M('order_kf')->add($data);
    	if($res){
    		$arr = M('order_kf')->where(['order_id'=>$data['order_id']])->select();
			$this->ajaxReturn(['status'=>1,'msg'=>'保存成功','arr'=>$arr]);exit;
    	}else{
			$this->ajaxReturn(['status'=>2,'msg'=>'保存失败']);exit;
    	}
    }
}